package com.toune.movie.base.myUtil;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.siberiadante.customdialoglib.EnsureDialog;
import com.toune.movie.R;
import com.toune.movie.base.App;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.myview.DownLoadApkDialog;
import com.toune.movie.base.myview.DownLoadDialog;
import com.toune.movie.base.myview.MusicPlayDialog;
import com.toune.movie.base.myview.MyLodingDialog;
import com.toune.movie.base.myview.ShareDialog;
import com.toune.movie.base.myview.ad.AdManager;
import com.toune.movie.mvp.activity.DownListActivity;
import com.toune.movie.mvp.activity.LoginActivity2;
import com.toune.movie.mvp.activity.MainActivity;
import com.toune.movie.service.MusicService;
import com.toune.movie.vo.DownVo;
import com.toune.movie.vo.MusicVo;
import com.toune.movie.vo.ShareVo;
import com.uuch.adlibrary.AdConstant;
import com.uuch.adlibrary.bean.AdInfo;
import com.uuch.adlibrary.transformer.ZoomOutPageTransformer;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxClipboardTool;
import com.vondear.rxtool.RxDataTool;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.RxImageTool;
import com.vondear.rxtool.RxNetTool;
import com.vondear.rxtool.view.RxToast;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.MoveType;
import com.yhao.floatwindow.Screen;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import gdut.bsx.share2.FileUtil;
import gdut.bsx.share2.Share2;
import gdut.bsx.share2.ShareContentType;

/**
 * Created by Administrator on 2018/5/2.
 */

public class MyUtil {
    public static List<AVObject> advList = new ArrayList<>();
    public static MusicPlayDialog musicPlayDialog;

    public static void getADlists() {
        advList = new ArrayList<>();
        AVQuery<AVObject> avQuery = new AVQuery<>(AppConstant.TAB_AD);
        avQuery.whereMatches("isShow", "1");
        avQuery.order("order");
        avQuery.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list != null) {
                        advList = list;
                    }
                }
            }
        });
    }

    public static void showADDialog(final Activity context) {
        List<AdInfo> adList = new ArrayList<>();
        if (advList.size() > 0) {
            for (int i = 0; i < advList.size(); i++) {
                AdInfo adInfo = new AdInfo();
                adInfo.setActivityImg(advList.get(i).getAVFile("file").getUrl());
                adInfo.setAdId(advList.get(i).getString("to"));
                adInfo.setUrl(advList.get(i).getString("content"));
                adInfo.setActivityImgId(i);
                adList.add(adInfo);
            }
            /**
             * 创建广告活动管理对象
             */
            AdManager adManager = new AdManager(context, adList);
            adManager.setOnImageClickListener(new AdManager.OnImageClickListener() {
                @Override
                public void onImageClick(View view, AdInfo advInfo) {
                    switch (advInfo.getAdId()) {
                        case AppConstant.ALIPAY:
                            //跳转到支付宝
                            RxClipboardTool.copyText(context, advInfo.getUrl());
                            if (!checkApkExist(context, "com.eg.android.AlipayGphone")) {
                                return;
                            }
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
                            //从当前应用跳转到另一个应用中
                            intent = context.getPackageManager().getLaunchIntentForPackage("com.eg.android.AlipayGphone");
                            context.startActivity(intent);
                            break;
                        case AppConstant.TAOBAO:
                            if (!checkApkExist(context, "com.taobao.taobao")) {
                                return;
                            }
                            Intent intentShare = new Intent();
                            intentShare.setAction("Android.intent.action.VIEW");
                            Uri uri = Uri.parse(advInfo.getUrl()); // 商品地址
                            intentShare.setData(uri);
                            intentShare.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
                            context.startActivity(intentShare);
                            break;
                        case AppConstant.SHARE:
                            ShareVo shareVo = new ShareVo();
                            AVObject avObject = advList.get(advInfo.getActivityImgId());
                            shareVo.setImagUrl(advInfo.getActivityImg());
                            shareVo.setFileName(avObject.getString("fileName"));
                            shareVo.setTitle("糖泥影院");
                            shareVo.setUrl(advInfo.getUrl());
                            if (avObject.getString("shareType") != null) {
                                switch (avObject.getString("shareType")) {
                                    case "0":
                                        //文本
                                        shareVo.setShareType(ShareContentType.TEXT);
                                        break;
                                    case "1":
                                        //图片
                                        shareVo.setShareType(ShareContentType.IMAGE);
                                        break;
                                    case "2":
                                        //文件
                                        shareVo.setShareType(ShareContentType.FILE);
                                        break;
                                    case "3":
                                        //音频
                                        shareVo.setShareType(ShareContentType.AUDIO);
                                        break;
                                    case "4":
                                        //视频
                                        shareVo.setShareType(ShareContentType.VIDEO);
                                        break;
                                }
                            }
                            showShareDialog(context, shareVo);
                            break;
                    }
                }
            })
                    .setBounciness(10)
                    .setSpeed(4)
                    .setOverScreen(true)
                    .setWidthPerHeight(0.75f)
                    .setOnCloseClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                        adManager.dismissAdDialog();
                        }
                    })
                    .setPageTransformer(new ZoomOutPageTransformer())
                    .showAdDialog(AdConstant.ANIM_UP_TO_DOWN);
        }
    }

    private static String galleryPath = Environment.getExternalStorageDirectory()
            + File.separator + "toune"
            + File.separator + "share" + File.separator;

    public static void showShareDialog(final Context context, final ShareVo shareVo) {
        switch (shareVo.getShareType()) {
            case ShareContentType.IMAGE:
                ThreadPoolManager.getInstatnce().createShortThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL imageURl = new URL(shareVo.getImagUrl());
                            URLConnection con = imageURl.openConnection();
                            con.connect();
                            InputStream inputStream = con.getInputStream();
                            String fileName = galleryPath + shareVo.getFileName();
                            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                            RxImageTool.save(bitmap, fileName, Bitmap.CompressFormat.PNG);
                            Uri fileUri = FileUtil.getFileUri(context, ShareContentType.IMAGE, RxFileTool.getFileByPath(fileName));
                            new Share2.Builder((Activity) context)
                                    // 指定分享的文件类型
                                    .setContentType(ShareContentType.IMAGE)
                                    // 设置要分享的文件 Uri
                                    .setShareFileUri(fileUri)
                                    // 设置分享选择器的标题
                                    .setTitle(shareVo.getTitle())
                                    .build()
                                    // 发起分享
                                    .shareBySystem();
                            inputStream.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;
            case ShareContentType.TEXT:
                new Share2.Builder((Activity) context)
                        .setContentType(ShareContentType.TEXT)
                        // 设置要分享的文本内容
                        .setTextContent(shareVo.getUrl())
                        .setTitle(shareVo.getTitle())
                        .build()
                        .shareBySystem();
                break;
            case ShareContentType.AUDIO:
                new Share2.Builder((Activity) context)
                        .setContentType(ShareContentType.AUDIO)
                        .setShareFileUri(getAudioContentUri(context, RxFileTool.getFileByPath(shareVo.getUrl())))
                        .setTitle(shareVo.getTitle())
                        .setTextContent(shareVo.getFileName())
                        .build()
                        .shareBySystem();
                break;
        }

    }

    private static Uri getAudioContentUri(Context context, File audioFile) {
        Uri uri = null;
        String filePath = audioFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/audio/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }

            cursor.close();
        }
        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Audio.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
        }

        return uri;
    }

    /**
     * 调用系统浏览器
     *
     * @param context
     * @param url
     */
    public static void intentToLocalChrom(Context context, String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        context.startActivity(intent);
    }

    private static void tellSystemPhoto(Context context, Bitmap bmp, String fileName) {
        //通知相册更新
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(RxFileTool.getFileByPath(fileName));
        intent.setData(uri);
        context.sendBroadcast(intent);
    }

    public static void showDownDialog(Context context, MusicVo.DataBean downVo) {
//        if (AVUser.getCurrentUser() == null) {
//            RxToast.info("请先登录");
//            RxActivityTool.skipActivity(context, LoginActivity2.class);
//            return;
//        }
        DownLoadDialog downLoadDialog = new DownLoadDialog(context, downVo);
        downLoadDialog.show();
        downLoadDialog.setCanceledOnTouchOutside(false);
    }

    /**
     * 显示等待框
     *
     * @param context
     */
    public static void showProDialog(Context context) {
        showProDialog(context, null);
    }

    public static void showProDialog(Context context, String str) {
        if (!MyLodingDialog.newInstance(context, str).isShowing()) {
            MyLodingDialog.newInstance(context, str).show();
        }
    }

    /**
     * 取消等待框
     */
    public static void hidProDialog() {
        MyLodingDialog.hideMySelf();
    }

    /**
     * 多颜色文本显示
     */
    public static Spanned getMoreStyleText(String[] strings, String[] colors) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            stringBuilder.append("<font color=\"" + colors[i] + "\">" + strings[i] + "</font>");
        }
        return Html.fromHtml(stringBuilder.toString());
    }

    /**
     * 获取本地IP地址
     *
     * @param context
     * @return
     */
    public static String getLocalIpAddress(Context context) {
        try {
            if (RxNetTool.isWifi(App.getInstance())) {
                //获取wifi服务
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                //判断wifi是否开启
                if (!wifiManager.isWifiEnabled()) {
                    wifiManager.setWifiEnabled(true);
                }
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                String ip = (ipAddress & 0xFF) + "." +
                        ((ipAddress >> 8) & 0xFF) + "." +
                        ((ipAddress >> 16) & 0xFF) + "." +
                        (ipAddress >> 24 & 0xFF);
                return ip;
            } else {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                            return inetAddress.getHostAddress().toString();
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    //判断某个应用是否存在
    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 从asset路径下读取对应json文件转String输出
     *
     * @param mContext
     * @return
     */
    public static String getJsonFileFromAssets(Context mContext, String fileName) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder();
        AssetManager am = mContext.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sb.delete(0, sb.length());
        }
        return sb.toString().trim();
    }

    /**
     * 获取ASSETS文件夹下的路径，只是基本路径
     *
     * @param fileName 这是文件的绝对路径 如html/index.html
     * @return 返回一个可以直接loadUrl的路径
     */
    public static String getHtmlFilePathFromAssets(String fileName) {
        String path = "";
        path = "file:///android_asset/" + fileName;
        return path;
    }

    /**
     * 对double类型的数值保留指定位数的小数。<br>
     * 该方法舍入模式：向“最接近的”数字舍入，如果与两个相邻数字的距离相等，则为向上舍入的舍入模式。<br>
     * <b>注意：</b>如果精度要求比较精确请使用 keepPrecision(String number, int precision)方法
     *
     * @param number    要保留小数的数字
     * @param precision 小数位数
     * @return double 如果数值较大，则使用科学计数法表示
     */
    public static double keepPrecision(double number, int precision) {
        BigDecimal bg = new BigDecimal(number);
        return bg.setScale(precision, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 对float类型的数值保留指定位数的小数。<br>
     * 该方法舍入模式：向“最接近的”数字舍入，如果与两个相邻数字的距离相等，则为向上舍入的舍入模式。<br>
     * <b>注意：</b>如果精度要求比较精确请使用 keepPrecision(String number, int precision)方法
     *
     * @param number    要保留小数的数字
     * @param precision 小数位数
     * @return float 如果数值较大，则使用科学计数法表示
     */
    public static float keepPrecision(float number, int precision) {
        BigDecimal bg = new BigDecimal(number);
        return bg.setScale(precision, BigDecimal.ROUND_HALF_UP).floatValue();
    }

    public static void intentToLocalFile(Context context, String localPath) {
        Intent fileIntent = RxFileTool.getFileIntent(localPath, "*/*");
        context.startActivity(fileIntent);
    }

    public static MusicPlayDialog showMusicPlayDialog(Context context, MusicVo.DataBean musicVo, String localPahth, int position) {
        if (musicPlayDialog == null || !musicPlayDialog.isShowing()) {
            musicPlayDialog = new MusicPlayDialog(context, musicVo, localPahth, position);
        } else {
            musicPlayDialog.resetMusic(musicVo, localPahth, position);
        }
        musicPlayDialog.show();
        return musicPlayDialog;
    }

    public static String getAppMusicPath() {
        return RxFileTool.getSDCardPath() + "toune/music";
    }

    public static String getAppVideoPath() {
        return RxFileTool.getSDCardPath() + "momo/video";
    }

    public static String getAppFilePath() {
        return RxFileTool.getSDCardPath() + "toune/file";
    }

    public static void showMusicFloatWindow(final MusicVo.DataBean dataBean) {
        if (FloatWindow.get() == null) {
            ImageView imageView = new ImageView(App.getInstance());
            Glide.with(App.getInstance()).load(dataBean.getPic()).apply(new RequestOptions().circleCrop()).into(imageView);
            Animation rotate = AnimationUtils.loadAnimation(App.getInstance(), R.anim.dialog_loading_animation);
            imageView.startAnimation(rotate);
            FloatWindow
                    .with(App.getInstance())
                    .setView(imageView)
                    .setWidth(Screen.width, 0.2f) //设置悬浮控件宽高
                    .setHeight(Screen.height, 0.2f)
                    .setX(Screen.width, 0.8f)
                    .setY(Screen.height, 0.3f)
                    .setMoveType(MoveType.slide, 0, 0)
                    .setMoveStyle(500, new BounceInterpolator())
//                .setViewStateListener(mViewStateListener)
//                .setPermissionListener(mPermissionListener)
                    .setDesktopShow(false)
                    .build();
            FloatWindow.get().show();
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     if (MyUtil.musicPlayDialog == null || !MyUtil.musicPlayDialog.isShowing()) {
                        MyUtil.showMusicPlayDialog(RxActivityTool.currentActivity(), dataBean, null, -1);
                    }
//                    FloatWindow.get().hide();
                }
            });
            imageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (MyUtil.musicPlayDialog != null && MyUtil.musicPlayDialog.isShowing()) {

                    } else {
                        FloatWindow.get().hide();
                        MusicService.stopThis(App.getInstance());
                    }
                    return true;
                }
            });
        } else {
            FloatWindow.get().show();
        }
    }

    /**
     * 获取前一个星期
     * 后一个星期只需将其中的-i改为+i即可
     *
     * @return
     */
    public static List<String> getTitles() {
        List<String> titles = new ArrayList<String>();
        String mYear; // 当前年
        String mMonth; // 月
        String mDay;
        int current_day;
        int current_month;
        int current_year;

        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        current_day = c.get(Calendar.DAY_OF_MONTH);
        current_month = c.get(Calendar.MONTH);
        current_year = c.get(Calendar.YEAR);
        for (int i = 0; i < 7; i++) {
            c.clear();//记住一定要clear一次
            c.set(Calendar.MONTH, current_month);
            c.set(Calendar.DAY_OF_MONTH, current_day);
            c.set(Calendar.YEAR, current_year);
            c.add(Calendar.DATE, -i);//j记住是DATE
            mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
            mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前日份的日期号码
            mYear = String.valueOf(c.get(Calendar.YEAR));// 获取当前年份
            String date = mYear + "年" + mMonth + "月" + mDay + "日";
            titles.add(date);
        }
        return titles;
    }

    public static String getAppZipPath() {
        return RxFileTool.getSDCardPath() + "alipay/file";
    }

    /**
     * 创建 单个 文件
     *
     * @param filePath 待创建的文件路径
     * @return 结果码
     */
    public static File createFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            return file;
        }
        if (filePath.endsWith(File.separator)) {// 以 路径分隔符 结束，说明是文件夹
            return null;
        }

        //判断父目录是否存在
        if (!file.getParentFile().exists()) {
            //父目录不存在 创建父目录
            if (!file.getParentFile().mkdirs()) {
                return null;
            }
        }

        //创建目标文件
        try {
            if (file.createNewFile()) {//创建文件成功
                return file;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return null;
    }

    public static final int FLAG_SUCCESS = 1;//创建成功
    public static final int FLAG_EXISTS = 2;//已存在
    public static final int FLAG_FAILED = 3;//创建失败

    /**
     * 创建 文件夹
     *
     * @param dirPath 文件夹路径
     * @return 结果码
     */
    public static int createDir(String dirPath) {

        File dir = new File(dirPath);
        //文件夹是否已经存在
        if (dir.exists()) {
            return FLAG_EXISTS;
        }
        if (!dirPath.endsWith(File.separator)) {//不是以 路径分隔符 "/" 结束，则添加路径分隔符 "/"
            dirPath = dirPath + File.separator;
        }
        //创建文件夹
        if (dir.mkdirs()) {
            return FLAG_SUCCESS;
        }

        return FLAG_FAILED;
    }
}
